package com.taxigang.client.uibinder;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
import com.taxigang.client.Session;
import com.taxigang.client.TaxiGangConstants;
import com.taxigang.client.TaxiGangHandler;
import com.taxigang.client.ui.map.MapView.PanelType;
import com.taxigang.shared.AwardInfo;
import com.taxigang.shared.TaxiGangInfo;
import com.taxigang.shared.TaxiGanguserInfo;

public class MyTaxiGangs extends TaxiGangPanel {

	private static MyTaxiGangsUiBinder uiBinder = GWT
	.create(MyTaxiGangsUiBinder.class);

	interface MyTaxiGangsUiBinder extends UiBinder<Widget, MyTaxiGangs> {
	}

	@UiField Button nextButton;
	@UiField Button previousButton;
	@UiField Button messagesButton;
	@UiField Button deleteButton;
	@UiField Button leaveButton;
	@UiField Button awardButton;
	//	@UiField Button leaderFbProfileButton;
	//	@UiField Button leaderAwardsButton;
	@UiField Panel myTaxiGangsVerticalPanel;
	@UiField Button closeButton;
	@UiField Label startAddressLabel;
	@UiField Label destinationAddressLabel;
	@UiField Label journeyBeginsLabel;
	//	@UiField Label leaderLabel;
	//	@UiField Label member1Label;
	//	@UiField Label member2Label;
	//	@UiField Label member3Label;
	//	@UiField Label member4Label;
	//	@UiField Label member5Label;
	//	@UiField Label member6Label;
	//	@UiField Label member7Label;

	@UiField Label startAddressContentLabel;
	@UiField Label destinationAddressContentLabel;
	@UiField Label journeyBeginsContentLabel;

	//	@UiField Label leaderContentLabel;
	//	@UiField Label member1ContentLabel;
	//	@UiField Label member2ContentLabel;
	//	@UiField Label member3ContentLabel;
	@UiField Label headerLabel;

	private TextArea[]listAwardTextArea;
	private AggregateArticleRating[]listAwardRatings;


	public static TaxiGangConstants taxiGangConstants = GWT.create(TaxiGangConstants.class);


	public MyTaxiGangs() {
		initWidget(uiBinder.createAndBindUi(this));
		//myTaxiGangsText.setText(taxiGangConstants.sorry());
		startAddressLabel.setText(taxiGangConstants.startAddress());
		destinationAddressLabel.setText(taxiGangConstants.enterDestinationAddress());
		journeyBeginsLabel.setText(taxiGangConstants.departureTime());
		closeButton.setText(taxiGangConstants.close());
		//		leaderLabel.setText("Leader");
		//		member1Label.setText("Member1");
		//		member2Label.setText("Member2");
		//		member3Label.setText("Member3");
		//		member4Label.setText("Member4");
		//		member5Label.setText("Member5");
		//		member6Label.setText("Member6");
		//		member7Label.setText("Member7");

		//		leaderFbProfileButton.setText("FB");
		//		leaderAwardsButton.setText("Awards");

		messagesButton.setText(taxiGangConstants.messages());
		deleteButton.setText(taxiGangConstants.delete());
		leaveButton.setText(taxiGangConstants.leave());
		awardButton.setText(taxiGangConstants.award());

		messagesButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				// TODO store nickname
				taxiGangRoute.show(PanelType.MESSAGES);
			}
		});

		deleteButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				// TODO store nickname
				Session session = Session.getInstance();
				TaxiGangInfo[] infoList = session.getMyTaxiGangList();
				if (infoList.length > session.getCurrentMyTaxiGangIndex()){
					TaxiGangInfo taxiganginfo = infoList[session.getCurrentMyTaxiGangIndex()];
					Session.getInstance().setCurrentMyTaxiGang(taxiganginfo);
					TaxiGangHandler.getInstance().deleteTaxiGang(false);
				} else {
					throw new RuntimeException(infoList.toString());
				}
			}
		});

		leaveButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				// TODO store nickname
				Session session = Session.getInstance();
				TaxiGangInfo[] infoList = session.getMyTaxiGangList();
				if (infoList.length > session.getCurrentMyTaxiGangIndex()){
					TaxiGangInfo taxiganginfo = infoList[session.getCurrentMyTaxiGangIndex()];
					Session.getInstance().setCurrentMyTaxiGang(taxiganginfo);
					TaxiGangHandler.getInstance().leaveTaxiGang(false);
				} else {
					throw new RuntimeException(infoList.toString());
				}
			}
		});

		awardButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				Session session = Session.getInstance();
				TaxiGangInfo[] infoList = session.getMyTaxiGangList();
				if (infoList.length > session.getCurrentMyTaxiGangIndex()){
					TaxiGangInfo taxiganginfo = infoList[session.getCurrentMyTaxiGangIndex()];

					int i=0;
					for (TaxiGanguserInfo member : taxiganginfo.getMember()){
						AwardInfo awardInfo = new AwardInfo();
						awardInfo.setAuthorName(Session.getInstance().getLoginInfo().getNickname());
						int vote = listAwardRatings[i].vote;
						awardInfo.setPoints(vote);
						awardInfo.setAwardText(listAwardTextArea[i].getText());
						member.setAwarded(awardInfo);
						i++;
					}
					Session.getInstance().setCurrentMyTaxiGang(taxiganginfo);
					TaxiGangHandler.getInstance().award();
				} else {
					throw new RuntimeException(infoList.toString());
				}

			}
		});

		closeButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				// TODO store nickname
				taxiGangRoute.show(PanelType.SEARCH);
			}
		});

		nextButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				// TODO store nickname
				Session.getInstance().incCurrentMyTaxiGangIndex();
				show();
			}
		});

		previousButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				// TODO store nickname
				Session.getInstance().decCurrentMyTaxiGangIndex();
				show();
			}
		});

		//		leaderFbProfileButton.addClickHandler(new ClickHandler() {
		//
		//			@Override
		//			public void onClick(ClickEvent event) {
		//				// TODO store nickname
		//				Window.alert("show fb profile");
		//			}
		//		});
		//		leaderAwardsButton.addClickHandler(new ClickHandler() {
		//
		//			@Override
		//			public void onClick(ClickEvent event) {
		//				TaxiGangInfo taxiGangInfo = Session.getInstance().getCurrentMyTaxiGang();
		//
		//				TaxiGanguserInfo user = taxiGangInfo.getMember()[0];
		//				Session.getInstance().setCurrentShowAwardsUser(user);
		//
		//				taxiGangRoute.show(PanelType.AWARDS);
		//			}
		//		});

	}

	public void show(){
		super.show();


		int length = Session.getInstance().getMyTaxiGangList().length;
		TaxiGangInfo[] infoList = Session.getInstance().getMyTaxiGangList();
		int currentMyTaxiGangIndex = Session.getInstance().getCurrentMyTaxiGangIndex();
		if (infoList.length > 0){
			if (infoList.length==1){
				headerLabel.setText(taxiGangConstants.myTaxiGang());
			} else {
				int displayIndex = currentMyTaxiGangIndex+1;
				headerLabel.setText(taxiGangConstants.myTaxiGang()+" "+displayIndex+" of "+infoList.length);
			}
			TaxiGangInfo taxiganginfo = infoList[currentMyTaxiGangIndex];
			if ("CLOSED".equals(taxiganginfo.getStatus())){
				headerLabel.setText("Please Award");
			}
			String startAddress = taxiganginfo.getStart();
			if (startAddress.indexOf(",") >0){
				startAddress = startAddress.substring(0,startAddress.indexOf(","));
			}
			startAddressContentLabel.setText(startAddress);

			String destAddress = taxiganginfo.getDestination();
			if (destAddress.indexOf(",") >0){
				destAddress = destAddress.substring(0,destAddress.indexOf(","));	
			}
			destinationAddressContentLabel.setText(destAddress);
			//journeyBeginsContentLabel.setText(TaxiGangHandler.formatter.format(taxiganginfo.getLocalDepartureTime()));
			journeyBeginsContentLabel.setText(taxiganginfo.getDepartureTime());

			loadMemberListPanel(taxiganginfo);
			//			leaderContentLabel.setText(taxiganginfo.getLeaderName());
			//			member1ContentLabel.setText(taxiganginfo.getMemberName(0));
			//			member2ContentLabel.setText(taxiganginfo.getMemberName(1));
			//			member3ContentLabel.setText(taxiganginfo.getMemberName(2));

			//taxiGangRoute.showMyTaxiGangInMap(taxiganginfo,true);
		}

		nextButton.setVisible( infoList.length - currentMyTaxiGangIndex > 1);
		previousButton.setVisible(currentMyTaxiGangIndex > 0);

		TaxiGangInfo currentTaxiGangInfo = infoList[currentMyTaxiGangIndex];
		boolean closed = currentTaxiGangInfo.isClosed();

		messagesButton.setVisible(!closed);

		int noMembers = infoList[currentMyTaxiGangIndex].getNumMembers();
		leaveButton.setVisible(noMembers > 0 && !closed);
		deleteButton.setVisible(noMembers == 0 && !closed);

		//awards
		awardButton.setVisible(closed);

	}

	private void loadMemberListPanel(TaxiGangInfo taxiganginfo) {
		myTaxiGangsVerticalPanel.clear();
		listAwardTextArea = new TextArea[taxiganginfo.getMember().length];
		listAwardRatings = new AggregateArticleRating[taxiganginfo.getMember().length];
		int i=0;
		for (TaxiGanguserInfo user : taxiganginfo.getMember()){
			TextArea ta = new TextArea();
			AggregateArticleRating rating = new AggregateArticleRating();
			rating.vote = 5;

			if (i==0){
				//leader
				Widget p = createAdvancedForm("Leader:",taxiganginfo,user,ta,rating,new Integer(5));
				myTaxiGangsVerticalPanel.add(p);

			} else {
				//member
				Widget p = createAdvancedForm("Member:",taxiganginfo,user,ta,rating,new Integer(5));
				myTaxiGangsVerticalPanel.add(p);

			}
			listAwardTextArea[i] = ta;
			listAwardRatings[i] = rating;
			i++;

		}

	}

	/**
	 * Create a form that contains undisclosed advanced options.
	 */
	private Widget createAdvancedForm(String title, final TaxiGangInfo taxiganginfo ,final TaxiGanguserInfo info,TextArea ta, AggregateArticleRating rating,Integer vote) {
		boolean awarding = "CLOSED".equals(taxiganginfo.getStatus());
		if (awarding){

			ArticleRatingWidget articleRatingWidget =  new ArticleRatingWidget("articleId", false, true, HasHorizontalAlignment.ALIGN_CENTER, rating,vote);

			// Create a table to layout the form options
			FlexTable layout = new FlexTable();
			layout.setCellSpacing(6);
			//layout.setWidth("300px");
			FlexCellFormatter cellFormatter = layout.getFlexCellFormatter();

			//cellFormatter.addStyleName(0, 0, "leftLabel");

			// Add a title to the form
			//layout.setHTML(0, 0, "cwDisclosurePanelFormTitle");
			cellFormatter.setColSpan(0, 0, 2);
			cellFormatter.setHorizontalAlignment(
					0, 0, HasHorizontalAlignment.ALIGN_CENTER);

			// Add some standard form options
			Label titleLabel = new Label(info.getDisplayName());
			titleLabel.setStylePrimaryName("memberLabel");
			layout.setWidget(1, 0, titleLabel);
			layout.setWidget(1, 1, articleRatingWidget);
			//		    layout.setWidget(1, 1, new TextBox());
			//		    layout.setHTML(2, 0, "cwDisclosurePanelFormDescription");
			//		    layout.setWidget(2, 1, new TextBox());

			// Create some advanced options
			//		    HorizontalPanel genderPanel = new HorizontalPanel();
			//		    String[] genderOptions = {"cwDisclosurePanelFormGenderOptions"};
			//		    for (int i = 0; i < genderOptions.length; i++) {
			//		      genderPanel.add(new RadioButton("gender", genderOptions[i]));
			//		    }

			//		    Grid advancedOptions = new Grid(2, 2);
			//		    advancedOptions.setCellSpacing(6);
			//		    advancedOptions.setHTML(0, 0, "Show in Facebook");
			//		    Button showInFBButton = new Button();
			//		    showInFBButton.addClickHandler(new ClickHandler() {
			//				
			//				@Override
			//				public void onClick(ClickEvent event) {
			//					Window.Location.assign("http://www.facebook.com/"+info.getId()); 
			//					
			//				}
			//			});
			//		    advancedOptions.setWidget(0, 1, showInFBButton);
			//		    advancedOptions.setHTML(1, 0, "Show Award History");
			//		    Button showAwardHistoryButton = new Button();
			//		    showAwardHistoryButton.addClickHandler(new ClickHandler() {
			//				
			//				@Override
			//				public void onClick(ClickEvent event) {
			//					Window.alert("show alert history");
			//					
			//				}
			//			});
			//		    advancedOptions.setWidget(1, 1, showAwardHistoryButton);

			ta.setWidth("200px");
			ta.setHeight("100px");
			// Add advanced options to form in a disclosure panel
			DisclosurePanel advancedDisclosure = new DisclosurePanel(
			"Show Details");
			advancedDisclosure.setAnimationEnabled(true);
			advancedDisclosure.ensureDebugId("cwDisclosurePanel");
			advancedDisclosure.setContent(ta);
			layout.setWidget(3, 0, advancedDisclosure);
			cellFormatter.setColSpan(3, 0, 2);

			// Wrap the contents in a DecoratorPanel
			//		    DecoratorPanel decPanel = new DecoratorPanel();
			//		    decPanel.setWidget(layout);
			return layout;

		} else {
			// Create a table to layout the form options
			FlexTable layout = new FlexTable();
			layout.setCellSpacing(6);
			//layout.setWidth("300px");
			FlexCellFormatter cellFormatter = layout.getFlexCellFormatter();

			//cellFormatter.addStyleName(0, 0, "leftLabel");

			// Add a title to the form
			//layout.setHTML(0, 0, "cwDisclosurePanelFormTitle");
			cellFormatter.setColSpan(0, 0, 2);
			cellFormatter.setHorizontalAlignment(
					0, 0, HasHorizontalAlignment.ALIGN_CENTER);

			// Add some standard form options
			Label titleLabel = new Label(title);
			titleLabel.setStylePrimaryName("memberLabel");
			layout.setWidget(1, 0, titleLabel);
			Label displayNameLabel = new Label(info.getDisplayName());
			displayNameLabel.setStylePrimaryName("memberLabel");
			layout.setWidget(1, 1, displayNameLabel);
			//	    layout.setWidget(1, 1, new TextBox());
			//	    layout.setHTML(2, 0, "cwDisclosurePanelFormDescription");
			//	    layout.setWidget(2, 1, new TextBox());

			// Create some advanced options
			//	    HorizontalPanel genderPanel = new HorizontalPanel();
			//	    String[] genderOptions = {"cwDisclosurePanelFormGenderOptions"};
			//	    for (int i = 0; i < genderOptions.length; i++) {
			//	      genderPanel.add(new RadioButton("gender", genderOptions[i]));
			//	    }
			Grid advancedOptions = new Grid(1, 2);
			advancedOptions.setCellSpacing(6);
			//advancedOptions.setHTML(0, 0, "Show in Facebook");
			Button showInFBButton = new Button("Show in Facebook");
			showInFBButton.addClickHandler(new ClickHandler() {

				@Override
				public void onClick(ClickEvent event) {
					Window.open("http://www.facebook.com/"+info.getId(),"",""); 

				}
			});
			advancedOptions.setWidget(0, 0, showInFBButton);
			//advancedOptions.setHTML(1, 0, "Show Award History");
			Button showAwardHistoryButton = new Button("Show Award History");
			showAwardHistoryButton.addClickHandler(new ClickHandler() {

				@Override
				public void onClick(ClickEvent event) {
					TaxiGanguserInfo user = taxiganginfo.getMember()[0];
					Session.getInstance().setCurrentShowAwardsUser(user);

					taxiGangRoute.show(PanelType.AWARDS);
				}
			});
			advancedOptions.setWidget(0, 1, showAwardHistoryButton);

			// Add advanced options to form in a disclosure panel
			DisclosurePanel advancedDisclosure = new DisclosurePanel(
			"Show Details");
			advancedDisclosure.setAnimationEnabled(true);
			advancedDisclosure.ensureDebugId("cwDisclosurePanel");
			advancedDisclosure.setContent(advancedOptions);
			layout.setWidget(3, 0, advancedDisclosure);
			cellFormatter.setColSpan(3, 0, 2);

			// Wrap the contents in a DecoratorPanel
			//	    DecoratorPanel decPanel = new DecoratorPanel();
			//	    decPanel.setWidget(layout);
			return layout;
		}
	}
}
